package com.sogoodsoft.service.crm;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.sogoodsoft.dao.common.CommonHibernateDao;
import com.sogoodsoft.dao.crm.VisitDao;
import com.sogoodsoft.entity.account.User;
import com.sogoodsoft.entity.app.SysClass;
import com.sogoodsoft.entity.crm.Smstask;
import com.sogoodsoft.entity.crm.Visit;
import com.sogoodsoft.service.account.AccountManager;
import com.sogoodsoft.service.common.AbstractService;

@Component
@Transactional
public class VisitService extends AbstractService<Visit,Long> {

    @Autowired
    private VisitDao visitDao;
    
    @Autowired
    private SmstaskService taskService;
    
    @Autowired
    private AccountManager accountManager;
    

    @SuppressWarnings({"unchecked" })
    @Override
    public CommonHibernateDao getDao() {
        return visitDao;
    }

	/* 
	 * 如果需要短信提示，提前一小时发送提示短信
	 * 如果修改时要短信提示，没添加的加上短信，添加过的修改短信内容
	 */
	@Override
	public void save(Visit t) {		
		
		//保存拜访信息
		visitDao.save(t);
		
		//新建或更新短信
		if(t.getNextalert().longValue()==1){
			Smstask task = taskService.findBySounceId(t.getId());
			if(task==null){
				task = new Smstask();
			}
			User user = accountManager.getUser(t.getVisitorid());
			task.setTarget(user.getMobile());
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(t.getNextdate());
			calendar.add(Calendar.HOUR_OF_DAY, -1);//提前一个小时
			task.setPlantime(calendar.getTime());
			SimpleDateFormat sdf = new SimpleDateFormat("HH点mm分");
			task.setMsg("至好CRM温馨提示："+user.getName()+"，您好，今天"+sdf.format(t.getNextdate())+"您与"
					+t.getCustomername()+"有个预约，请您及时到场，祝您工作愉快！系统自动发送，请忽回复！");
			SysClass type = taskService.getSmsType(Visit.smstype);
			task.setType(type);
			task.setUserid(user.getId());
			task.setUsername(user.getName());
			taskService.save(task);
		}
			
	}
    
    

}
